<template>
  <div>
    <el-dialog
      :visible.sync="dialogVisible"
      :before-close="closeDialog"
      :show-close="true"
      :append-to-body="true"
      :class="{'mobile-el-dialog mobile-el-dialog-form': showMobilePage}"
      :close-on-click-modal="false"
      class="global-dailog-style resource-dialog"
    >
      <div :style="{maxHeight: '80vh'}" class="body-form">
        <!-- 上刊状态 -->
        <journalStatus ref="journalStatus" :model-data="modelData" :row-span="rowSpan" :is-signed="isSigned" dialog/>
        <!-- 上刊价格 -->
        <journal v-if="showJournal" ref="journal" :model-data="modelData" :row-span="rowSpan" :is-signed="isSigned" :rule-parent-key="['journalKey','morePriceInfo']" dialog/>
        <!-- 成本信息 -->
        <cost v-if="showCost" ref="cost" :model-data="modelData" :row-span="rowSpan" :rule-parent-key="['costInfoKey']" dialog/>
        <!-- 分成信息 -->
        <morePrice ref="morePrice" :model-data="modelData" :row-span="rowSpan" dialog/>
        <!-- 更多上刊信息 -->
        <moreJournal v-if="showMoreJournal" ref="moreJournal" :model-data="modelData" :is-signed="isSigned" :rule-parent-key="['moreJournalKey']" dialog/>
        <fixed-pagination style="width: 100%; padding: 0; margin: 0; border-radius: 0px 0px 8px 8px">
          <div class="edit-btn-container center mobile-btn-group">
            <el-button :loading="loading" size="small" class="btn mobile-btn-flex" type="primary" @click.stop="handelOk">确定</el-button>
            <el-button size="small" class="btn cancel-btn-style" type="default" plain @click.stop="closeDialog">取消</el-button>
          </div>
        </fixed-pagination>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import Title from '@/components/Title';
import { mapState } from 'vuex';
import mixins from './mixins';
import { editJournalInfo } from '@/api/resource';
import journalStatus from '../create/model/journalStatus';
import journal from '../create/model/journal';
import cost from '../create/model/cost';
import moreJournal from '../create/model/moreJournal';
import morePrice from '../create/model/morePrice';
import { isJournalPlatform } from '@/views/resource/create/resourceData';

export default {
  components: { Title, journalStatus, journal, cost, moreJournal, morePrice },
  mixins: [mixins],
  props: {
    additionalKey: {
      type: Object,
      default: () => ({
        articlesPrice: {},
        costPrice: {
          starMapTwenty: {}, // 【抖音】星图报价1-20s
          starMapSixty: {}, // 【抖音】星图报价20-60s
          starMapAboveSixty: {}, // 【抖音】星图报价60s以上
          contentCollectionPrice: {}, // 【抖音】内容合集单坑位报价
          customVideo: {}, // 【B站】定制视频
          implantationVideo: {}, // 【B站】植入视频
          publishTrends: {}, // 【B站】直发动态
          forwardTrends: {}, // 【B站】转发动态
          publish: {}, // 【微博】非原创直发
          forward: {}, // 【微博】非原创转发
          originalContent: {}, // 【微博】原创图文发布
          originalVideo: {} // 【微博】原创视频发布
        },
        monthReportPrice: {}, // 本月报备价(即本月平台价格)
        nextMonthReportPrice: {}, // 次月报备价(即次月平台价格)
        monthNotReportPrice: {}, // 本月非报备价
        nextMonthNotReportPrice: {}, // 次月非报备价
        monthReportPriceCost: {
          imageTextPrice: {},
          videoPrice: {}
        },
        monthNotReportPriceCost: {
          imageTextPrice: {},
          videoPrice: {}
        },
        nextMonthReportPriceCost: {
          imageTextPrice: {},
          videoPrice: {}
        },
        nextMonthNotReportPriceCost: {
          imageTextPrice: {},
          videoPrice: {}
        },
        microTaskCost: {
          publish: {},
          forward: {},
          originalContent: {},
          originalVideo: {}
        },
        followContractBroker: [],
        freeAuth: {
          isConfirm: true,
          cost: ''
        },
        otherFreePlatform: {
          isConfirm: true,
          cost: ''
        },
        hasShopPrice: {
          isConfirm: false,
          cost: ''
        },
        addBrand: {
          isConfirm: true,
          cost: ''
        },
        retentionAllowed: {
          isConfirm: true,
          timeLimit: ''
        },
        allowCar: {
          isConfirm: true,
          cost: ''
        },
        carCommission: {
          isConfirm: true,
          cost: ''
        }
      })
    }
  },
  data() {
    return {
      modelData: {
        journalKey: {},
        costInfoKey: {},
        moreJournalKey: {},
        morePriceInfo: {}
      },
      loading: false,
      dialogVisible: false,
      editResourceForm: {
        id: '',
        journalStatus: {
          selectionStatus: '',
          journalStatus: '',
          publicationTime: '',
          publicationMonth: '',
          journalNode: ''
        },
        journalPrice: {
          articlesPrice: {},
          monthReportPrice: {}, // 本月报备价(即本月平台价格)
          nextMonthReportPrice: {}, // 次月报备价(即次月平台价格)
          monthNotReportPrice: {}, // 本月非报备价
          nextMonthNotReportPrice: {}, // 次月非报备价
          shortVideoPrice: ''
        },
        costInfo: {
          costPrice: {
            starMapTwenty: {}, // 【抖音】星图报价1-20s
            starMapSixty: {}, // 【抖音】星图报价20-60s
            starMapAboveSixty: {}, // 【抖音】星图报价60s以上
            contentCollectionPrice: {}, // 【抖音】内容合集单坑位报价
            customVideo: {}, // 【B站】定制视频
            implantationVideo: {}, // 【B站】植入视频
            publishTrends: {}, // 【B站】直发动态
            forwardTrends: {}, // 【B站】转发动态
            publish: {}, // 【微博】非原创直发
            forward: {}, // 【微博】非原创转发
            originalContent: {}, // 【微博】原创图文发布
            originalVideo: {} // 【微博】原创视频发布
          },
          monthReportPriceCost: {
            imageTextPrice: {},
            videoPrice: {}
          },
          monthNotReportPriceCost: {
            imageTextPrice: {},
            videoPrice: {}
          },
          nextMonthReportPriceCost: {
            imageTextPrice: {},
            videoPrice: {}
          },
          nextMonthNotReportPriceCost: {
            imageTextPrice: {},
            videoPrice: {}
          },
          microTaskCost: {
            publish: {},
            forward: {},
            originalContent: {}, // 【微博】原创图文发布
            originalVideo: {} // 【微博】原创视频发布
          },
          dynamicKey: []
        },
        morePriceInfo: {
          profitSharingRemark: '',
          profitSharingRatio: '',
          guaranteeRemark: '',
          guaranteePrice: '',
          dynamicKey: []
        },
        moreJournalKey: {
          isFrameOut: '',
          isVoiceAnchor: '',
          masterFit: '',
          orderRequest: '',
          recommendRank: '',
          mutualselect: '',
          adExample: '',
          originVideoRequst: '',
          brandExperience: '',
          privateDeductionTaxRate: '',
          freeAuth: {
            isConfirm: true,
            cost: ''
          },
          otherFreePlatform: {
            isConfirm: true,
            cost: ''
          },
          hasShopPrice: {
            isConfirm: true,
            cost: ''
          },
          addBrand: {
            isConfirm: true,
            cost: ''
          },
          retentionAllowed: {
            isConfirm: true,
            timeLimit: ''
          },
          allowCar: {
            isConfirm: true,
            cost: ''
          },
          carCommission: {
            isConfirm: true,
            cost: ''
          },
          dynamicKey: []
        }
      },
      defaultForm: {},
      isSigned: false
    };
  },
  computed: {
    ...mapState({
      'showMobilePage': state => state.app.showMobilePage
    }),
    isCommon() {
      const arr = ['小红书', '抖音', '微博', 'B站'];
      return !arr.includes(this.modelData.platformTypeName);
    },
    isJournalPlatform() {
      return isJournalPlatform(this.modelData.platformTypeName);
    },
    showJournal() {
      return this.isJournalPlatform || this.isExitArrayItem(this.modelData.journalKey.dynamicKey) || this.isExitArrayItem(this.modelData.morePriceInfo.dynamicKey);
    },
    showCost() {
      return !this.isCommon || this.isExitArrayItem(this.modelData.costInfoKey.dynamicKey);
    },
    showMoreJournal() {
      return this.isJournalPlatform || this.isExitArrayItem(this.modelData.moreJournalKey.dynamicKey);
    },
    refs() {
      const refs = ['morePrice', 'journalStatus'];
      if (this.showCost) {
        refs.push('cost');
      }
      if (this.showJournal) {
        refs.push('journal');
      }
      if (this.showMoreJournal) {
        refs.push('moreJournal');
      }
      return refs;
    },
    dynamicParentKeys() {
      return ['journalKey', 'costInfoKey', 'morePriceInfo', 'moreJournalKey'];
    }
  },
  methods: {
    openDialog(params) {
      const { data } = params || {};
      this.defaultFOrm = _.cloneDeep(this.editResourceForm);
      this.modelData = this.formatData(_.cloneDeep(data));
      this.getDynamic(this.modelData, this.dynamicParentKeys);
      this.isSigned = data.signStatus === 1; // 已签约
      this.dialogVisible = true;
    },
    closeDialog() {
      this.dialogVisible = false;
      this.editResourceForm = this.defaultFOrm;
    },
    formatData(data) {
      const formData = JSON.parse(JSON.stringify(data));
      if (!formData.additionalKey.microTaskCost) {
        formData.additionalKey.microTaskCost = {};
      }
      if (!formData.additionalKey.microTaskCost.originalContent) {
        formData.additionalKey.microTaskCost.originalContent = {
          value: '',
          remark: ''
        };
      }
      if (!formData.additionalKey.microTaskCost.originalVideo) {
        formData.additionalKey.microTaskCost.originalVideo = {
          value: '',
          remark: ''
        };
      }
      const additionalKeys = Object.keys(this.additionalKey);
      formData.morePriceInfo.profitSharingRatio !== null ? (formData.morePriceInfo.profitSharingRatio += '') : '';
      additionalKeys.forEach(key => {
        const outValue = formData.additionalKey[key];
        if (!outValue && outValue !== 0 && outValue !== false) {
          this.$set(formData.additionalKey, key, this.additionalKey[key]);
        }
        if (Object.prototype.toString.call(formData.additionalKey[key]) === '[object Object]') {
          const innerKeys = Object.keys(formData.additionalKey[key]);
          innerKeys.forEach(innerKey => {
            const value = formData.additionalKey[key];
            if (!value && value !== 0 && value !== false) {
              this.$set(formData.additionalKey[key], innerKey, this.additionalKey[key][innerKey]);
            }
          });
        }
      });
      return formData;
    },
    async handelOk() {
      const valid = await this.validateForm().catch((err) => { console.log(err); });
      if (!valid) {
        this.$message.warning('请检查信息是否填写完整');
        return;
      }
      const params = _.cloneDeep(this.editResourceForm);
      const additionalKey = this.modelData.additionalKey;

      const additionalKeys = ['journalPrice', 'costInfo', 'journalStatus', 'moreJournalKey'];
      additionalKeys.forEach(parentKey => {
        Object.keys(params[parentKey]).forEach(key => {
          if (additionalKey[key] || additionalKey[key] === 0 || additionalKey[key] === false) {
            params[parentKey][key] = additionalKey[key];
          }
        });
      });
      params.journalPrice.dynamicKey = this.modelData.journalKey.dynamicKey;
      params.costInfo.dynamicKey = this.modelData.costInfoKey.dynamicKey;
      params.morePriceInfo = this.modelData.morePriceInfo;
      params.moreJournalKey.dynamicKey = this.modelData.moreJournalKey.dynamicKey;
      params.id = this.modelData.systemId;
      this.loading = true;
      editJournalInfo(params).then(res => {
        this.loading = false;
        if (res.code === 200) {
          this.$message.success('修改成功');
          this.$emit('success');
        }
        this.closeDialog();
      }).catch(() => {
        this.loading = false;
      });
    },
    isExitArrayItem(arr) {
      return arr && arr.length;
    }
  }
};
</script>
<style lang="scss" scoped>
.resource-dialog {
  ::v-deep {
    .el-dialog {
      width: 960px;
    }
    .el-dialog__body {
      padding: 16px 24px 24px 24px !important;
    }
  }
}
.width240-time {
  width: 240px;
}
.body-form {
  padding-bottom: 50px;
  @include scrollBar($x: hidden, $y: auto, $width: 6px);
}
.width240 {
  width: 240px;
  &::v-deep {
    .el-input__inner {
      width: 240px;
    }
  }
}
::v-deep {
  .dynamicKey-label {
    .el-form-item__label {
      display: flex;
      align-items: center;
      justify-content: flex-end;
    }
    .el-form-item__error {
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
      max-width: 240px;
    }
  }
}
.edit-btn-container {
  display: flex;
  justify-content: center;
}
</style>
